﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;
using Microsoft.Xna.Framework.Media;
using SMARTMobile.Common;
using SMARTMobile.Models.Local;
using SMARTMobile.Models.UI;
using SMARTMobile.Utilities;
using SMARTMobile.ViewModels;
using System.Windows.Media;
using C1.Phone.FlexGrid;
using System.Collections;
using SMARTMobile.WinPhone;
using Telerik.Windows.Controls;
using SmartMobile.Data;
using SMARTMobile.Models;
using SMARTMobile.WinPhone.Helpers;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace SMARTMobile.Views
{
    public partial class NhapDuLieuPage
    {
        private List<string> _IntFields = new List<string>()
        {
            "Qty",
            //"MerchandisingSize"
        };

        private List<string> _FloatFields = new List<string>()
        {
            "WhosesaleVolume",
            "RetailVolume",
            "WhosesaleValue",
            "RetailValue",
            "ContributionByVolume",
            "ContributionByVolume",
            "ContributionAmt"
        };

        private string currentCell;
        private bool isxplainOutDoor;
        private bool isxplainInDoor;
        private bool isMerchandising;
        private List<C1FlexGrid> _listFlexGrid;
        private List<RadExpanderControl> _listExpendable;
        private C1FlexGrid _currentFlexGrid;
        private int _currentRowPopUp;
        private int _currentIndex;
        private int _currentRowGrid;
        private int _imageQuantity;
        private bool _isPopupLoaded;
        private int _currentGridItemsCount;
        private string _currentImageName;
        private GlobalInformation.AdvancedTypeEnum _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.None;
        NhapDuLieuViewModel _viewModel;
        public NhapDuLieuPage()
        {
            InitializeComponent();
            this._listFlexGrid = new List<C1FlexGrid>();
            this._listExpendable = new List<RadExpanderControl>();
            this.Loaded += NhapDuLieuPage_Loaded;
        }

        void NhapDuLieuPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this._viewModel = new NhapDuLieuViewModel();
            this.DataContext = this._viewModel;
        }

        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string msg;
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
            {
                if (!string.IsNullOrEmpty(msg) && msg.Contains("ExplainOutDoor"))
                {
                    isxplainOutDoor = true;
                    string tempName = msg.Split(';')[1];
                    currentCell = tempName;
                    _currentRowPopUp = int.Parse(tempName.Split(':')[1]);
                    _currentIndex = int.Parse(tempName.Split(':')[2]);
                    _imageQuantity = int.Parse(tempName.Split(':')[3]);

                    //this.CurrentOutEx.IsExpanded = true;
                }

                if (!string.IsNullOrEmpty(msg) && msg.Contains("ExplainInDoor"))
                {
                    isxplainInDoor = true;
                    string tempName = msg.Split(';')[1];
                    currentCell = tempName;
                    _currentRowPopUp = int.Parse(tempName.Split(':')[1]);
                    _currentIndex = int.Parse(tempName.Split(':')[2]);
                    _imageQuantity = int.Parse(tempName.Split(':')[3]);
                    //this.CurrentInEx.IsExpanded = true;
                }

                if (!string.IsNullOrEmpty(msg) && msg.Contains("ExplainMerchandising"))
                {
                    isMerchandising = true;
                    string tempName = msg.Split(';')[1];
                    currentCell = tempName;
                    _currentRowPopUp = int.Parse(tempName.Split(':')[1]);
                    _currentIndex = int.Parse(tempName.Split(':')[2]);
                    _imageQuantity = int.Parse(tempName.Split(':')[3]);
                    // this.OutletNokiaMercEx.IsExpanded = true;
                }
            }
        }

        public BitmapImage GetLastImage()
        {
            var imageList = new ObviousCollection<Image>();
            using (var library = new MediaLibrary())
            {
                Picture photoFromLibrary = library.Pictures[library.Pictures.Count - 1];
                BitmapImage latestBitmapImage = new BitmapImage();
                latestBitmapImage.SetSource(photoFromLibrary.GetImage());

                return latestBitmapImage;
            }
        }

        private void NhapDuLieuPage_BeginningEdit(object sender, CellEditEventArgs e)
        {
            if (this._currentFlexGrid != null && _currentFlexGrid.Columns[e.Column].Tag != null)
            {
                if (_currentFlexGrid.Columns[e.Column].Tag.ToString() == "OutletNokiaMerchandisingPotential" && (sender as C1FlexGrid).Columns[e.Column].ColumnName == "WherePicture")
                {
                    isMerchandising = true;
                    ////_imageQuantity = string.IsNullOrEmpty((sender as C1FlexGrid)[e.Row, "Qty"].ToString()) ? 1 : int.Parse((sender as C1FlexGrid)[e.Row, "Qty"].ToString());
                    _imageQuantity = 1;

                    if (_imageQuantity > 0)
                    {
                        this.ChupHinh.IsOpen = true;
                        List<TakePictureModel> items = new List<TakePictureModel>();
                        string picture = (sender as C1FlexGrid)[e.Row, "WherePicture"].ToString();
                        if (picture != string.Empty && int.Parse(picture.Split('/')[0]) > 0)
                        {
                            for (int i = 0; i < _imageQuantity; i++)
                            {
                                string imageName = "Merchandising\\" + this._currentFlexGrid[e.Row, "Customerkey"] + "~" + this._currentFlexGrid[e.Row, "MerchandisingCode"] + "~" + i.ToString() + ".jpeg";
                                TakePictureModel item = new TakePictureModel();
                                item.PictureURL = "";
                                item.Index = i;
                                item.CaptureTime = DateTime.Now;
                                item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                                item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.Merchandising;
                                if (ImageUtilities.CheckFileExist(imageName))
                                {
                                    item.PictureURL = imageName;
                                    item.PictureSource = ImageUtilities.LoadImageFromIsolatedStorage(imageName);
                                }

                                items.Add(item);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < _imageQuantity; i++)
                            {
                                TakePictureModel item = new TakePictureModel();
                                item.PictureURL = "";
                                item.Index = i;
                                item.CaptureTime = DateTime.Now;
                                item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                                item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.Merchandising;
                                item.PictureSource = new BitmapImage(new Uri(@"/Images/noimage.jpg", UriKind.RelativeOrAbsolute));
                                items.Add(item);
                            }
                        }

                        GlobalInformation.ListTakePictureModel = items;
                        listButton.ItemsSource = items;

                        this.SavePreviousGrid();
                        GlobalInformation.CurrentColumnRowNhapDuLieu = e.Column.ToString() + ":" + e.Row.ToString();
                    }

                    _currentRowGrid = e.Row;
                    e.Cancel = true;
                }
                else if (_currentFlexGrid.Columns[e.Column].Tag.ToString() == "CurrentOutDoorDisplay" && (sender as C1FlexGrid).Columns[e.Column].ColumnName == "WherePicture")
                {
                    isxplainOutDoor = true;
                    _imageQuantity = string.IsNullOrEmpty((sender as C1FlexGrid)[e.Row, "Qty"].ToString()) ? 1 : int.Parse((sender as C1FlexGrid)[e.Row, "Qty"].ToString());

                    if (_imageQuantity > 0)
                    {
                        this.ChupHinh.IsOpen = true;
                        // Todo: Get image taken from isolated
                        List<TakePictureModel> items = new List<TakePictureModel>();

                        string picture = (sender as C1FlexGrid)[e.Row, "WherePicture"].ToString();
                        if (picture != string.Empty && int.Parse(picture.Split('/')[0]) > 0)
                        {
                            for (int i = 0; i < _imageQuantity; i++)
                            {
                                string imageName = "NhapDuLieu\\" + "OUT~" + this._currentFlexGrid[e.Row, "Customerkey"] + "~" + this._currentFlexGrid[e.Row, "PhoneVendorCode"] + "~" + this._currentFlexGrid[e.Row, "OutDoorTypeCode"] + "~" + i.ToString() + ".jpeg";

                                TakePictureModel item = new TakePictureModel();
                                item.PictureURL = "";
                                item.Index = i;
                                item.CaptureTime = DateTime.Now;
                                item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                                item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.ExplainOutDoor;
                                if (ImageUtilities.CheckFileExist(imageName))
                                {
                                    item.PictureURL = imageName;
                                    item.PictureSource = ImageUtilities.LoadImageFromIsolatedStorage(imageName);
                                }

                                items.Add(item);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < _imageQuantity; i++)
                            {
                                TakePictureModel item = new TakePictureModel();
                                item.PictureURL = "";
                                item.Index = i;
                                item.CaptureTime = DateTime.Now;
                                item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                                item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.ExplainOutDoor;
                                item.PictureSource = new BitmapImage(new Uri(@"/Images/noimage.jpg", UriKind.RelativeOrAbsolute));
                                items.Add(item);
                            }
                        }

                        GlobalInformation.ListTakePictureModel = items;
                        listButton.ItemsSource = items;
                        this.SavePreviousGrid();
                        GlobalInformation.CurrentColumnRowNhapDuLieu = e.Column.ToString() + ":" + e.Row.ToString();

                    }

                    _currentRowGrid = e.Row;
                    e.Cancel = true;
                }
                else if (_currentFlexGrid.Columns[e.Column].Tag.ToString() == "CurrentInDoorDoorDisplay" && (sender as C1FlexGrid).Columns[e.Column].ColumnName == "WherePicture")
                {
                    isxplainInDoor = true;
                    _imageQuantity = string.IsNullOrEmpty((sender as C1FlexGrid)[e.Row, "Qty"].ToString()) ? 1 : int.Parse((sender as C1FlexGrid)[e.Row, "Qty"].ToString());

                    if (_imageQuantity > 0)
                    {
                        this.ChupHinh.IsOpen = true;
                        List<TakePictureModel> items = new List<TakePictureModel>();
                        string picture = (sender as C1FlexGrid)[e.Row, "WherePicture"].ToString();
                        if (picture != string.Empty && int.Parse(picture.Split('/')[0]) > 0)
                        {
                            for (int i = 0; i < _imageQuantity; i++)
                            {
                                string imageName = "NhapDuLieu\\" + "IN~" + this._currentFlexGrid[e.Row, "Customerkey"] + "~" + this._currentFlexGrid[e.Row, "PhoneVendorCode"] + "~" + this._currentFlexGrid[e.Row, "InDoorTypeCode"] + "~" + i.ToString() + ".jpeg";

                                TakePictureModel item = new TakePictureModel();
                                item.PictureURL = "";
                                item.Index = i;
                                item.CaptureTime = DateTime.Now;
                                item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                                item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.ExplainInDoor;
                                if (ImageUtilities.CheckFileExist(imageName))
                                {
                                    item.PictureURL = imageName;
                                    item.PictureSource = ImageUtilities.LoadImageFromIsolatedStorage(imageName);
                                }

                                items.Add(item);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < _imageQuantity; i++)
                            {
                                TakePictureModel item = new TakePictureModel();
                                item.PictureURL = "";
                                item.Index = i;
                                item.CaptureTime = DateTime.Now;
                                item.CustomerKey = (sender as C1FlexGrid)[e.Row, "Customerkey"].ToString();
                                item.TakePictureTypeEnum = GlobalInformation.TakePictureTypeEnum.ExplainInDoor;
                                item.PictureSource = new BitmapImage(new Uri(@"/Images/noimage.jpg", UriKind.RelativeOrAbsolute));
                                items.Add(item);
                            }
                        }

                        GlobalInformation.ListTakePictureModel = items;

                        listButton.ItemsSource = items;
                        this.SavePreviousGrid();
                        GlobalInformation.CurrentColumnRowNhapDuLieu = e.Column.ToString() + ":" + e.Row.ToString();
                    }

                    _currentRowGrid = e.Row;
                    e.Cancel = true;
                }
            }
        }

        private void FlexGrid_Loaded(object sender, RoutedEventArgs e)
        {
            var vm = DataContext as NhapDuLieuViewModel;
            this._listFlexGrid.Add(sender as C1FlexGrid);

            if ((isMerchandising || isxplainInDoor || isxplainOutDoor) && this._listFlexGrid.Count == vm.OutletAdvanceInforListingObservable.Count)
            {
                isMerchandising = false;
                isxplainInDoor = false;
                isxplainOutDoor = false;
                this._listExpendable[_currentIndex].IsExpanded = true;

                if (!_isPopupLoaded)
                {
                    // show pop up
                    LoadPopup();
                }
            }
        }

        private void FlexGrid_LoadedRows(object sender, EventArgs e)
        {
            isMerchandising = false;
        }

        private void LoadPopup()
        {
            if (_imageQuantity > 0)
            {
                this.ChupHinh.IsOpen = true;
                foreach (TakePictureModel item in GlobalInformation.ListTakePictureModel)
                {
                    if (item.Index == _currentRowPopUp)
                    {
                        item.PictureURL = _currentImageName;
                        item.PictureSource = ImageUtilities.LoadImageFromIsolatedStorage(item.PictureURL);
                    }
                }

                listButton.ItemsSource = GlobalInformation.ListTakePictureModel;

                _isPopupLoaded = true;
            }
        }

        private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
        {
            this._listExpendable.Add(sender as RadExpanderControl);
        }

        private void Save_OnTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var vm = DataContext as NhapDuLieuViewModel;
            foreach (var flexGrid in this._listFlexGrid)
            {
                if (flexGrid.Columns == null || flexGrid.Columns.Count == 0)
                {
                    continue;
                }

                switch (flexGrid.Columns[0].Tag.ToString())
                {
                    case "PhonevendorVolume":
                        {
                            vm.PhonevendorVolumeObservable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                PhonevenforVolumeExtend newObject = new PhonevenforVolumeExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.PhonevendorVolumeObservable.Add(newObject);
                            }
                        }

                        break;
                    case "OutletVendorContribution":
                        {
                            vm.OutletVendorContributionObserable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                OutltVendorContributionExtend newObject = new OutltVendorContributionExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.OutletVendorContributionObserable.Add(newObject);
                            }
                        }

                        break;
                    case "PriceRangeContribution":
                        {
                            vm.PriceRangeContributionObservable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                PriceRangeContributionExtend newObject = new PriceRangeContributionExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.PriceRangeContributionObservable.Add(newObject);
                            }
                        }

                        break;

                    case "CurrentOutDoorDisplay":
                        {
                            vm.CurrentOutDoorDisplayObservable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                CurrentOutDoorDisplayExtend newObject = new CurrentOutDoorDisplayExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.CurrentOutDoorDisplayObservable.Add(newObject);
                            }
                        }

                        break;
                    case "CurrentInDoorDoorDisplay":
                        {
                            vm.CurrentInDoorDoorDisplayObservable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                CurrentInDoorDisplayExtend newObject = new CurrentInDoorDisplayExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.CurrentInDoorDoorDisplayObservable.Add(newObject);
                            }
                        }

                        break;

                    case "OutetPGInformation":
                        {
                            vm.OutetPGInformationObservable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                OutletPGInformationExtend newObject = new OutletPGInformationExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.OutetPGInformationObservable.Add(newObject);
                            }
                        }

                        break;

                    case "OutletNokiaMerchandisingPotential":
                        {
                            vm.OutletNokiaMerchandisingPotentialObservable.Clear();
                            for (int i = 0; i < flexGrid.Rows.Count; i++)
                            {
                                OutletNokiaMerchandisingPotentialExtend newObject = new OutletNokiaMerchandisingPotentialExtend();
                                newObject.ID_PK = Guid.NewGuid();
                                foreach (var column in flexGrid.Columns)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, flexGrid[i, column].ToString());
                                }
                                vm.OutletNokiaMerchandisingPotentialObservable.Add(newObject);
                            }
                        }

                        break;
                }
            }

            vm.ExecuteSaveCommand(null);
        }

        private void SavePreviousGrid()
        {
            if (_currentFlexGrid == null)
            {
                return;
            }

            var vm = DataContext as NhapDuLieuViewModel;

            switch (_previousAdvancedTypeEnum)
            {
                case GlobalInformation.AdvancedTypeEnum.None:

                    break;
                case GlobalInformation.AdvancedTypeEnum.PhonevendorVolume:
                    {
                        vm.PhonevendorVolumeObservable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            PhonevenforVolumeExtend newObject = new PhonevenforVolumeExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }

                            vm.PhonevendorVolumeObservable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.OutletVendorContribution:
                    {
                        vm.OutletVendorContributionObserable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            OutltVendorContributionExtend newObject = new OutltVendorContributionExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }
                            vm.OutletVendorContributionObserable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.PriceRangeContribution:
                    {
                        vm.PriceRangeContributionObservable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            PriceRangeContributionExtend newObject = new PriceRangeContributionExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }
                            vm.PriceRangeContributionObservable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.CurrentOutDoorDisplay:
                    {
                        vm.CurrentOutDoorDisplayObservable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            CurrentOutDoorDisplayExtend newObject = new CurrentOutDoorDisplayExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }
                            vm.CurrentOutDoorDisplayObservable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.CurrentInDoorDoorDisplay:
                    {
                        vm.CurrentInDoorDoorDisplayObservable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            CurrentInDoorDisplayExtend newObject = new CurrentInDoorDisplayExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }
                            vm.CurrentInDoorDoorDisplayObservable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.OutetPGInformation:
                    {
                        vm.OutetPGInformationObservable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            OutletPGInformationExtend newObject = new OutletPGInformationExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }
                            vm.OutetPGInformationObservable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.OutletNokiaMerchandisingPotential:
                    {
                        vm.OutletNokiaMerchandisingPotentialObservable.Clear();
                        for (int i = 0; i < _currentFlexGrid.Rows.Count; i++)
                        {
                            OutletNokiaMerchandisingPotentialExtend newObject = new OutletNokiaMerchandisingPotentialExtend();
                            newObject.ID_PK = Guid.NewGuid();
                            foreach (var column in _currentFlexGrid.Columns)
                            {
                                if (_currentFlexGrid[i, column] != null)
                                {
                                    DataRowToObjectHelper.ConvertTo(newObject, column.ColumnName, _currentFlexGrid[i, column].ToString());
                                }
                            }
                            vm.OutletNokiaMerchandisingPotentialObservable.Add(newObject);
                        }
                    }

                    break;
                case GlobalInformation.AdvancedTypeEnum.OutletMDContribution:
                    break;
            }

            vm.SavePreviousAdvanceType(_previousAdvancedTypeEnum);
        }

        private void RadExpanderControl_OnExpandedStateChanged(object sender, ExpandedStateChangedEventArgs e)
        {
            if (e.IsExpanded)
            {
                OutletAdvanceInforListingModel selectedAdvance =
                    (sender as RadExpanderControl).DataContext as OutletAdvanceInforListingModel;
                if (selectedAdvance != null)
                {
                    SavePreviousGrid();
                    ////SaveCurrentPictureGrid();

                    var vm = DataContext as NhapDuLieuViewModel;
                    int index = vm.OutletAdvanceInforListingObservable.IndexOf(selectedAdvance);
                    _currentIndex = index;

                    ////if (this._listFlexGrid.Count == 0 || this._listFlexGrid.Count < index)
                    ////{
                    ////    return;
                    ////} 

                    this._currentFlexGrid = this._listFlexGrid[index];
                    if (this._currentFlexGrid.Columns != null && this._currentFlexGrid.Columns.Count > 0)
                    {
                        for (int i = 0; i < this._listExpendable.Count; i++)
                        {
                            if (i != index)
                            {
                                this._listExpendable[i].IsExpanded = false;
                            }
                        }
                    }
                    else
                    {
                        foreach (var advanceInforTable in selectedAdvance.ChildInfo.OrderBy(x => x.FieldShowOrder))
                        {
                            Column col = new Column();
                            col.Header = advanceInforTable.FieldShow;
                            col.Tag = advanceInforTable.DataTable;
                            col.Width = GridLength.Auto;
                            col.MinWidth = 255;
                            col.ColumnName = advanceInforTable.FieldName;
                            if (_IntFields.Contains(advanceInforTable.FieldName))
                            {
                                col.DataType = typeof(int);
                            }

                            if (_FloatFields.Contains(advanceInforTable.FieldName))
                            {
                                col.DataType = typeof(float);
                            }

                            this._currentFlexGrid.Columns.Add(col);
                        }

                        this._currentFlexGrid.AutoSizeColumns(0, this._currentFlexGrid.Columns.Count - 1, 0, true, true);
                        this._currentFlexGrid.ColumnHeaderBackground = new SolidColorBrush(Colors.Gray);
                        this._currentFlexGrid.ColumnHeaderForeground = new SolidColorBrush(Colors.Black);
                        this._currentFlexGrid.GridLinesVisibility = GridLinesVisibility.All;
                        this._currentFlexGrid.AutoComplete = true;
                        this._currentFlexGrid.BeginningEdit += NhapDuLieuPage_BeginningEdit;
                        switch (_currentFlexGrid.Columns[0].Tag.ToString())
                        {
                            case "PhonevendorVolume":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.PhonevendorVolume;
                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["PhoneVendorCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "PhoneVendorName"
                                    });

                                    this._currentFlexGrid.Columns["PhoneVendorCode"].Visible = false;

                                    for (int i = 0; i < vm.PhonevendorVolumeObservable.Count; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.PhonevendorVolumeObservable[i], column.ColumnName);
                                        }
                                    }
                                }

                                break;
                            case "OutletVendorContribution":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.OutletVendorContribution;
                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["OutletVendorKey"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "OutletVendorName"
                                    });

                                    this._currentFlexGrid.Columns["OutletVendorKey"].Visible = false;

                                    for (int i = 0; i < vm.OutletVendorContributionObserable.Count; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.OutletVendorContributionObserable[i], column.ColumnName);
                                        }
                                    }

                                }

                                break;
                            case "PriceRangeContribution":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.PriceRangeContribution;
                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["PriceRangeCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "PriceRangeName"
                                    });

                                    this._currentFlexGrid.Columns["PriceRangeCode"].Visible = false;
                                    
                                    for (int i = 0; i < vm.PriceRangeContributionObservable.Count; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());

                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.PriceRangeContributionObservable[i], column.ColumnName);
                                        }
                                    }
                                }

                                break;

                            case "CurrentOutDoorDisplay":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.CurrentOutDoorDisplay;
                                    object tag = _currentFlexGrid.Columns[0].Tag;

                                    this._currentFlexGrid.Columns.Insert(0, new Column()
                                    {
                                        Header = "Customerkey",
                                        Tag = tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "Customerkey"
                                    });

                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["PhoneVendorCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "PhoneVendorName"
                                    });

                                    this._currentFlexGrid.Columns.Insert(2, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["OutDoorTypeCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "OutDoorTypeName"
                                    });

                                    this._currentFlexGrid.Columns["OutDoorTypeCode"].Visible = false;
                                    this._currentFlexGrid.Columns["PhoneVendorCode"].Visible = false;
                                    this._currentFlexGrid.Columns["Qty"].Visible = false;
                                    this._currentFlexGrid.Columns[0].Visible = false;

                                    _currentGridItemsCount = vm.CurrentOutDoorDisplayObservable.Count;
                                    isxplainOutDoor = true;
                                    for (int i = 0; i < _currentGridItemsCount; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.CurrentOutDoorDisplayObservable[i], column.ColumnName);
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(currentCell))
                                    {
                                        SaveImageAfterTaken("NhapDuLieu\\" + "OUT~", "NhapDuLieu");
                                        currentCell = string.Empty;
                                    }
                                }

                                break;
                            case "CurrentInDoorDoorDisplay":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.CurrentInDoorDoorDisplay;
                                    object tag = _currentFlexGrid.Columns[0].Tag;

                                    this._currentFlexGrid.Columns.Insert(0, new Column()
                                    {
                                        Header = "Customerkey",
                                        Tag = tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "Customerkey"
                                    });

                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["PhoneVendorCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "PhoneVendorName"
                                    });

                                    this._currentFlexGrid.Columns.Insert(2, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["InDoorTypeCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "InDoorTypeName"
                                    });

                                    this._currentFlexGrid.Columns["InDoorTypeCode"].Visible = false;
                                    this._currentFlexGrid.Columns["PhoneVendorCode"].Visible = false;
                                    this._currentFlexGrid.Columns["Qty"].Visible = false;
                                    this._currentFlexGrid.Columns[0].Visible = false;

                                    _currentGridItemsCount = vm.CurrentInDoorDoorDisplayObservable.Count;
                                    isxplainInDoor = true;
                                    for (int i = 0; i < _currentGridItemsCount; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.CurrentInDoorDoorDisplayObservable[i], column.ColumnName);
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(currentCell))
                                    {
                                        SaveImageAfterTaken("NhapDuLieu\\" + "IN~", "NhapDuLieu");
                                        currentCell = string.Empty;
                                    }
                                }

                                break;

                            case "OutetPGInformation":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.OutetPGInformation;
                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["PhoneVendorCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "PhoneVendorName"
                                    });

                                    this._currentFlexGrid.Columns["PhoneVendorCode"].Visible = false;

                                    for (int i = 0; i < vm.OutetPGInformationObservable.Count; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.OutetPGInformationObservable[i], column.ColumnName);
                                        }
                                    }
                                }

                                break;

                            case "OutletNokiaMerchandisingPotential":
                                {
                                    _previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.OutletNokiaMerchandisingPotential;
                                    object tag = _currentFlexGrid.Columns[0].Tag;

                                    this._currentFlexGrid.Columns.Insert(0, new Column()
                                    {
                                        Header = "Customerkey",
                                        Tag = tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "Customerkey"
                                    });

                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["MerchandisingCode"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "MerchandisingName"
                                    });

                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["MerchandisingSize"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "MerchandisingSize"
                                    });

                                    this._currentFlexGrid.Columns["MerchandisingCode"].Visible = false;
                                    this._currentFlexGrid.Columns["MerchandisingSize"].Visible = false;
                                    this._currentFlexGrid.Columns["Qty"].Visible = false;
                                    this._currentFlexGrid.Columns[0].Visible = false;

                                    _currentGridItemsCount = vm.OutletNokiaMerchandisingPotentialObservable.Count;
                                    isMerchandising = true;
                                    for (int i = 0; i < _currentGridItemsCount; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                    DataRowToObjectHelper.GetValueFromPropertyName(
                                        vm.OutletNokiaMerchandisingPotentialObservable[i], column.ColumnName);
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(currentCell))
                                    {
                                        SaveImageAfterTakenMerchandising("Merchandising\\", "Merchandising");
                                        currentCell = string.Empty;
                                    }
                                }

                                break;
                            case "OutletMDContribution":
                                {
                                    object tag = _currentFlexGrid.Columns[0].Tag;

                                    this._currentFlexGrid.Columns.Insert(1, new Column()
                                    {
                                        Header = this._currentFlexGrid.Columns["MDKey"].Header,
                                        Tag = this._currentFlexGrid.Tag,
                                        Width = GridLength.Auto,
                                        MinWidth = 255,
                                        ColumnName = "OutletMDName"
                                    });

                                    this._currentFlexGrid.Columns[0].Visible = false;

                                    for (int i = 0; i < vm.OutletMDContributionObservable.Count; i++)
                                    {
                                        this._currentFlexGrid.Rows.Add(new Row());
                                        foreach (var column in this._currentFlexGrid.Columns)
                                        {
                                            this._currentFlexGrid[i, column] =
                                                DataRowToObjectHelper.GetValueFromPropertyName(
                                                    vm.OutletMDContributionObservable[i], column.ColumnName);
                                        }
                                    }
                                }

                                break;
                        }

                        for (int i = 0; i < this._listExpendable.Count; i++)
                        {
                            if (i != index)
                            {
                                this._listExpendable[i].IsExpanded = false;
                            }
                        }
                    }
                }
            }
        }

        private void ExitModalWindow_Click(object sender, RoutedEventArgs e)
        {
            if (this._currentFlexGrid != null && !string.IsNullOrEmpty(GlobalInformation.CurrentColumnRowNhapDuLieu))
            {
                string[] item = GlobalInformation.CurrentColumnRowNhapDuLieu.Split(':');
                string value = GlobalInformation.ListTakePictureModel.Count(a => a.PictureURL != "").ToString() + "/" + GlobalInformation.ListTakePictureModel.Count().ToString();
                this._currentFlexGrid[int.Parse(item[1]), int.Parse(item[0])] = value;
                if (isMerchandising)
                {
                    this._previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.OutletNokiaMerchandisingPotential;
                    this.SavePreviousGrid();
                }
                else if (isxplainOutDoor)
                {
                    this._previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.CurrentOutDoorDisplay;
                    this.SavePreviousGrid();
                }
                else
                {
                    this._previousAdvancedTypeEnum = GlobalInformation.AdvancedTypeEnum.CurrentInDoorDoorDisplay;
                    this.SavePreviousGrid();
                }
            }

            this.ChupHinh.IsOpen = false;
            isMerchandising = false;
            isxplainInDoor = false;
            isxplainOutDoor = false;
            _isPopupLoaded = false;
        }

        private void SaveImageAfterTaken(string prefix, string folder)
        {
            int row = int.Parse(currentCell.Split(':')[4]);
            // prefix: "NhapDuLieu\\" + "OUT~"
            // folder: "NhapDuLieu"
            string code = string.Empty;
            if (isxplainOutDoor)
            {
                code = "OutDoorTypeCode";
            }
            else
            {
                code = "InDoorTypeCode";
            }

            _currentImageName = prefix + this._currentFlexGrid[row, "Customerkey"] + "~" + this._currentFlexGrid[row, "PhoneVendorCode"] + "~" + this._currentFlexGrid[row, code] + "~" + _currentRowPopUp.ToString() + ".jpeg";

            Utilities.ImageUtilities.SaveToJpeg(GetLastImage(), _currentImageName, folder);
        }

        private void SaveImageAfterTakenMerchandising(string prefix, string folder)
        {
            int row = int.Parse(currentCell.Split(':')[4]);
            // prefix: "NhapDuLieu\\" + "OUT~"
            // folder: "NhapDuLieu"
            _currentImageName = prefix + this._currentFlexGrid[row, "Customerkey"] + "~" + this._currentFlexGrid[row, "MerchandisingCode"] + "~" + _currentRowPopUp.ToString() + ".jpeg";

            Utilities.ImageUtilities.SaveToJpeg(GetLastImage(), _currentImageName, folder);
        }

        private void DuyetImageButton_OnTap(object sender, GestureEventArgs e)
        {
            // Click="SelectedImageType_OnClick"
            if (e.OriginalSource is Image)
            {
                if ((e.OriginalSource as Image).Tag != null)
                {
                    TakePictureModel model = (e.OriginalSource as Image).Tag as TakePictureModel;
                    if (isMerchandising)
                    {
                        //SaveOutletNokia();
                        GlobalInformation.StateImageType = 0;
                        NavigationService.Navigate(new Uri("/Views/ChupHinhCuaHangPage.xaml?msg=" + "Merchandising;" + "0" + ":" + model.Index.ToString() + ":" + _currentIndex.ToString() + ":" + _imageQuantity.ToString() + ":" + _currentRowGrid.ToString(), UriKind.Relative));
                    }
                    else if (isxplainOutDoor)
                    {
                        //SaveOutDoorDisplay();
                        GlobalInformation.StateImageType = 0;
                        NavigationService.Navigate(new Uri("/Views/ChupHinhCuaHangPage.xaml?msg=" + "NhapDuLieuOut;" + "0" + ":" + model.Index.ToString() + ":" + _currentIndex.ToString() + ":" + _imageQuantity.ToString() + ":" + _currentRowGrid.ToString(), UriKind.Relative));
                    }
                    else if (isxplainInDoor)
                    {
                        //SaveInDoorDoorDisplay();
                        GlobalInformation.StateImageType = 0;
                        NavigationService.Navigate(new Uri("/Views/ChupHinhCuaHangPage.xaml?msg=" + "NhapDuLieuIn;" + "0" + ":" + model.Index.ToString() + ":" + _currentIndex.ToString() + ":" + _imageQuantity.ToString() + ":" + _currentRowGrid.ToString(), UriKind.Relative));
                    }
                }
            }
        }
    }
}